<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h1>员工列表</h1>
        </div>
      </template>
      <!-- 搜索 -->
      <div class="search">
        <el-form :inline="true" :model="searchBox">
          <el-form-item label="名称">
            <el-input v-model="searchBox.name"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchBox.phone"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="searchFN" color="#06988B">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 功能按钮 -->
      <div class="fnBtn">
        <el-button class="addbtn" type="primary" @click="openAddUser">
          添加员工</el-button>
          <el-button class="addbtn" type="warning" @click="batchDelete">
            批量删除</el-button> 
      </div>
      <!-- 表格 -->
      <el-table :data="userList" v-loading="loading" style="width: 100%" :show-overflow-tooltip="true" stripe border @selection-change="handleSelectionChange">
        <el-table-column type="selection"  width="55" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="departmentId" label="部门" >
          <template #default="scope">
            {{ getDepartmentName(scope.row.departmentId) }}
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职位" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="entryTime" label="入职时间" >
          <template #default="scope">
            {{ FormatDate(scope.row.entryTime,'yyyy-MM-dd') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button class="editbtn" @click="handleEdit(scope.row)"  type="primary">
              <Edit class="el-size" />修改
            </el-button>
            <el-button class="editbtn" type="warning" @click="handleDelete(scope.row)" 
              >
              <Delete class="el-size" />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" v-model:current-page="Page" v-model:page-size="Limit"
        :page-sizes="[1, 10, 20, 30]" :small="small" :disabled="disabled" :background="false"
        layout="total, prev, pager, next, sizes, jumper" :total="Number(total)" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-card>
    <!-- 添加员工弹窗 -->
    <!-- 弹框 -->
    <el-dialog v-model="dialogVisible" :title="dtitle" width="600px" :before-close="handleClose"
      :close-on-click-modal="false">
      <!-- 表单 -->
      <el-form :model="addForm" ref="addFormRef" :rules="addRules" label-position="top" label-width="100px">
        <!-- 弹窗 -->
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio value="男">男</el-radio>
            <el-radio value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="number" v-model="addForm.age"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <!-- <el-input v-model="addForm.departmentId"></el-input> -->
          <el-select v-model="addForm.departmentId" placeholder="请选择部门">
            <el-option v-for="item in departmentList" :key="item._id" :label="item.name" :value="item._id"></el-option>
          </el-select>
           
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="addForm.position"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="入职日期" prop="entryTime">
          <!-- <el-input v-model="addForm.entryTime"></el-input> -->
          <el-date-picker v-model="addForm.entryTime" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dtitle === '修改员工信息' ? false : true">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getUserListAPI, addUserAPI, editUserAPI, delUserAPI, delUsersAPI } from '../api/user';
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDepartmentListAPI } from '../api/department';
import { FormatDate } from '../utils/util';

const searchBox = ref({
  name: '',
  phone: '',
});

const searchFN = () => {
  getUserList();
};


//控制loading状态
const loading = ref(true);

//分页
const total = ref(0);
const small = ref(false);
const disabled = ref(false);
const Page = ref(1);
const Limit = ref(10);
const multipleSelection = ref([]); // 表格选中的数据
const departmentList:any = ref([]); // 部门列表数据

// 添加用户表单
const addForm: any = ref({});

//获取表单的请求数据
const userList = ref([]); // 表格数据
const dialogVisible = ref(false); // 控制弹窗开关
const addFormRef: any = ref(null); // 声明一个 ref 用于引用表单组件
const dtitle = ref('添加员工');

onMounted(() => {
  getUserList();
  getDepartmentList();
});
// 添加用户表单校验
const addRules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: '请输入正确的手机号',
      trigger: ['blur'],
    },
  ],
  departmentId: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  entryTime: [{ required: true, message: '请输入入职日期', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度在 6 到 18 个字符', trigger: ['blur'] },
  ],
  isUsing: [{ required: true, message: '请选择是否启用', trigger: 'blur' }],
});
// 获取员工列表
const getUserList = async () => {
  const res: any = await getUserListAPI({
    Name: searchBox.value.name,
    Phone: searchBox.value.phone,
    Page: Page.value,
    Limit: Limit.value,
  });
  userList.value = res.data;
  total.value = res.count;
  loading.value = false;
};
// 打开添加员工弹窗
const openAddUser = (event: any) => {
  // 重置按钮样式
  dtitle.value = '添加员工';
  dialogVisible.value = true;
};
// 修改表格数据
const handleEdit = (row: any) => {
  // 开启弹窗
  dtitle.value = '修改员工信息';
  dialogVisible.value = true;
  addForm.value = JSON.parse(JSON.stringify(row));
};
// 删除表格数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm('是否删除此员工?')
    .then(async () => {
      //调用删除接口
      await delUserAPI(row._id);
      ElMessage.success('删除成功');
      //删除完调用获取员工列表接口重新渲染
      getUserList();
    })
    .catch(() => {
      // catch error
      ElMessage.warning('您已取消删除');
    });
};

// 添加员工
const addUser = async () => {
  try {
    console.log(addForm.value);
    // 执行表单校验
    await addFormRef.value.validate();
    // 校验成功后发起添加请求
    if (!addForm.value._id) {
      await addUserAPI(addForm.value);
      ElMessage.success('添加成功');
    } else {
      await editUserAPI(addForm.value);
      ElMessage.success('修改成功');
    }
    // 关闭并重置弹窗
    handleClose();
    // 成功后通知父组件刷新表格
    getUserList();
  } catch (error) {
    ElMessage.error('表单校验失败,请检查输入');
    console.log(error);
  }
};
// 关闭添加员工弹窗
const handleClose = () => {
  dialogVisible.value = false;
  // 关闭清空表单
  addFormRef.value.resetFields();
  addForm.value = {
    name: '',
    phone: '',
    account: '',
    password: '',
    isUsing: 1,
  };
};
// 分页
const handleSizeChange = (val: any) => {
  Limit.value = val;
  getUserList();
};
//处理切换页码
const handleCurrentChange = (val: any) => {
  Page.value = val;
  getUserList();
};
// 处理表格选择
const handleSelectionChange = (val:any)=> {
  multipleSelection.value = val;
}
// 批量删除
const batchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的员工');
    return;
  }  
  const ids = multipleSelection.value.map((item: any) => item._id);
  ElMessageBox.confirm('是否删除选中的员工?')
    .then(async () => {
      //调用删除接口
      await delUsersAPI({ids});
      ElMessage.success('删除成功');
      //删除完调用获取员工列表接口重新渲染
      getUserList();
    })
}

// 获取所有部门
const getDepartmentList = async () => {
  const res: any = await getDepartmentListAPI({});
  departmentList.value = res.data;
};

// 查询部门名称
const getDepartmentName = (id: string) => {
  const department = departmentList.value.find((item: any) => item._id === id);
  return department ? department.name : ''; 
}
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

:deep(.search .search-form) {
  display: flex;
}

.pagination {
  margin-top: 20px;
}

.addbtn {
  margin-bottom: 20px;
}

::v-deep(.is-active) {
  background-color: #06988b;
  color: #fff;
}

::v-deep(.el-pager li.is-active) {
  // background-color: #06988b;
  color: #fff;
}
</style>
